import React, { Component } from "react";
// 引入store
import store from "../../redux/store";
// 引入action,专门用于创建action对象
import {createIncrementAction,createDecrementAction} from '../../redux/count_actions.js'
export default class Count extends Component {
  state = { count: 0 };

  componentDidMount() {
    //监测redux 中的状态的变化，只要发生变化，就调用render
    // 只要 redux 里面的状态发生改变就会调用store.subscribe
    // 也可以在app.jsx里面写
    // store.subscribe(() => {
    //   this.setState({});
    // });
  }

  // 加
  increment = () => {
    // store.getState(); 获取store里面的值
    const { value } = this.sellectNumber;
    // 分发任务
    // store.dispatch({ type: "increment", data: value * 1 });
    store.dispatch(createIncrementAction(value *1))
  };
  decrement = () => {
    const { value } = this.sellectNumber;
    // store.dispatch({ type: "decrement", data: value * 1 });
    store.dispatch(createDecrementAction(value *1))
  };
  incrementIfOdd = () => {
    const { value } = this.sellectNumber;
    const count = store.getState();
    if (count % 2 !== 0) {
    //   store.dispatch({ type: "increment", data: value * 1 });
    store.dispatch(createIncrementAction(value *1))
    }
  };
  incrementAsync = () => {
    setTimeout(() => {
      const { value } = this.sellectNumber;
    //   store.dispatch({ type: "increment", data: value * 1 });
    store.dispatch(createIncrementAction(value *1))
    }, 500);
  };
  render() {
    let { count } = this.state;
    return (
      <div>
        <h1>当前求和为：{store.getState()}</h1>
        <select ref={(c) => (this.sellectNumber = c)}>
          <option value="1"> 1 </option>
          <option value="2"> 2 </option>
          <option value="3"> 3 </option>
        </select>
        <button onClick={this.increment}>+</button>
        <button onClick={this.decrement}>-</button>
        <button onClick={this.incrementIfOdd}>当前求和为奇数再加</button>
        <button onClick={this.incrementAsync}>异步加</button>
      </div>
    );
  }
}
